<template>
  <div>
    <!-- 触发按钮 -->
    <el-button type="primary" @click="openDialog">打开对话框</el-button>
    
    <!-- 对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="表单验证示例"
      width="500px"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        @submit.prevent="handleSubmit"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="formData.username" 
            placeholder="请输入用户名"
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="formData.email" 
            placeholder="请输入邮箱"
          />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input 
            v-model="formData.phone" 
            placeholder="请输入手机号"
          />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="formData.description" 
            type="textarea" 
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'

// 响应式数据
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const loading = ref(false)

// 表单数据
const formData = reactive({
  username: '',
  email: '',
  phone: '',
  description: ''
})

// 表单验证规则
const formRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入描述', trigger: 'blur' },
    { min: 10, max: 200, message: '描述长度在 10 到 200 个字符', trigger: 'blur' }
  ]
})

// 打开对话框
const openDialog = () => {
  dialogVisible.value = true
  // 重置表单数据
  resetForm()
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 手动重置响应式数据
  Object.assign(formData, {
    username: '',
    email: '',
    phone: '',
    description: ''
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) {
    ElMessage.error('表单实例未初始化')
    return
  }
  
  try {
    loading.value = true
    
    // 关键：使用 await 等待验证完成
    const valid = await formRef.value.validate()
    
    if (valid) {
      // 验证通过，执行提交逻辑
      console.log('表单数据:', formData)
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      ElMessage.success('提交成功！')
      handleClose()
    } else {
      // 验证失败
      ElMessage.error('请检查表单填写是否正确')
    }
  } catch (error) {
    console.error('表单验证错误:', error)
    ElMessage.error('表单验证失败')
  } finally {
    loading.value = false
  }
}

// 监听对话框状态变化
const watchDialogVisible = () => {
  if (dialogVisible.value) {
    // 对话框打开后，确保表单实例已初始化
    nextTick(() => {
      if (formRef.value) {
        console.log('表单实例已初始化')
      }
    })
  }
}

// 使用 watch 监听对话框状态
import { watch } from 'vue'
watch(dialogVisible, watchDialogVisible)
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 